﻿$(function () {
    // Config popup manage friends
    $('.fbManageFriend').fancybox();
    // Show manage friends	
    $('#danhsachban').click(btnshowfriendonClick);
    // Hien thi loi moi ket ban
    $('#loimoiketban').click(btnmakefriendonClick);
    // Hien thi trang tim kiem ban
    $('#timkiemban').click(loadsearchfriendonClick);
    // click tim kiem
    // $('#btnsearchfriend').click(btnfindfriendonClick);    
});

//////////////////////////////////////////////////////

//******************************************
// Send request make friend
//******************************************
function sendreqmakefriend(ketbanobj) {
    var email = $('#emailds').val(),
		tempmabanbe1 = email,
		tempmabanbe2 = email,
		temptinhtrang = ketbanobj,		
		tempdatenow = new Date();
	
    var banbedata = {
		//MaKetBan: 1,
        MaBanBe1: tempmabanbe1,
        //MaBanBe2: tempmabanbe1,
        //NgayKetBan: tempdatenow,
        TinhTrang: temptinhtrang
	};
    $.ajax({
        url: $.configGlobal.uriSendRequestFriendAPI,
        type: $.configGlobal.protoPOST,
        dataType: $.configGlobal.dataJSON,
        contentType: $.configGlobal.ctnJSON,
        data: JSON.stringify(banbedata),
        // cache: false,
        // async: false,
        success: function (response) {
            if (response == null) {
                console.log("return data from send request make friend api is empty !");
                return false;
			}
            else {
                //hien thi yeu cau ket ban hien tai.
                btnfindfriendonClick()
                //loadresultsearchfriend($($.configGlobal.tabFindFriend));
                return false;
			}
		},
        error: function (request, status, msg) {
            console.log(msg);
            return false;
		}
	});
    return false;
}
//******************************************
// Load search friend
//******************************************
function loadsearchfriendonClick() {
    var $tableaddrow = $($.configGlobal.tabFindFriend),
    contentHTML = "";	
    // $tableaddrow
		// .empty()
		// .append($('<div class="khungsearchfriend"><div class="searchfri"><div class="searchfriend"><input id="textquery" type="text" value="ABCD" /></div><div class="btnsearchfriend"><a href="" id="btnsearchfriend" onclick="btnfindfriendonClick();return false;">Search</a></div></div><div class="messagetext">Nhập tên cần tìm.</div></div>'));
	$tableaddrow = $('<div class="khungsearchfriend"><div class="searchfri"><div class="searchfriend"><input id="textqueryext" type="text" value="ABCD" /></div><div class="btnsearchfriend"><a href="" id="btnsearchfriend" onclick="btnfindfriendonClick();return false;">Search</a></div></div><div class="messagetext">Nhập tên cần tìm.</div></div>');
    contentHTML = $tableaddrow.html();
    $('#test')
	.empty()
	.html(contentHTML);
    return false;
}

//******************************************
// Load result search friend
//******************************************
function loadresultsearchfriend(tab) {
    var $tableaddrow = tab,
        email = $('#emailds').val(),
        contentHTML = "",
        friend = $.configGlobal.AllFriend;
    if (!(friend instanceof Array)) {
        console.log("khong co ban nao trong danh sach");
        return false;
	}
    var friendsize = friend.length;
    if (friendsize < 1) {
        console.log("friend variable is empty");
        return false;
	}
    // $tableaddrow.empty();
    // $tableaddrow.append('<div class="khungsearchfriend"><div class="searchfriend"><input id="textquery" type="text" /></div><div class="btnsearchfriend"><a href="" id="btnsearchfriend">Search</a></div></div>');
	$tableaddrow = $('<div class="khungsearchfriend"><div class="searchfri"><div class="searchfriend"><input id="textqueryext" type="text" value="'+email+'" /></div><div class="btnsearchfriend"><a href="" id="btnsearchfriend" onclick="btnfindfriendonClick();return false;">Search</a></div></div><div class="messagetext">Nhập tên cần tìm.</div></div>');
    for (var i = 0; i < friendsize; i++) {
        var tempfriend = friend[i];
        if (tempfriend.HinhDaiDien == "0") {
            $tableaddrow.append('<div class="khungketbanul"><hr /><div class="khungketbanli" style="width:70%">{0}</div><div class="khungketbanli" style="width:30%"><a href="" id="ketban{1}" onclick="sendreqmakefriend({1});return false;">Kết bạn</a></div></div>'.format(tempfriend.TenTaiKhoan, tempfriend.MaTaiKhoan));
            // $tableaddrow.append('<script>$(function(){$("#ketban{0}").click(sendreqmakefriend("{}"));return false;});</script>'.format(tempfriend.MaTaiKhoan));
            tempfriend = null;
		}
        else if (tempfriend.HinhDaiDien == "1") {
            $tableaddrow.append('<div class="khungketbanul"><hr /><div class="khungketbanli" style="width:70%">{0}</div><div class="khungketbanli" style="width:30%">Đã là bạn</div></div>'.format(tempfriend.TenTaiKhoan, tempfriend.MaTaiKhoan));
            tempfriend = null;
		}
        else if (tempfriend.HinhDaiDien == "2") {
            $tableaddrow.append('<div class="khungketbanul"><hr /><div class="khungketbanli" style="width:70%">{0}</div><div class="khungketbanli" style="width:30%">Đang chờ kết bạn</div></div>'.format(tempfriend.TenTaiKhoan, tempfriend.MaTaiKhoan));
            tempfriend = null;
		}
	}
    contentHTML = $tableaddrow.html();
    $('#test')
	.empty()
	.html(contentHTML);
    return false;
}
//******************************************
// Declare function to clear row of table friend
//******************************************
function clearRowOfTable(objTable) {
	//     var tempTable = objTable;
	//     var countrow = tempTable.find('div').length;
	//     //None clear if table empty
	//     if (countrow < 1) {
	//         return;
	//	 }
	//     //Clear row
	//     tempTable
	//	 .find('div')
	//	 .remove()
	//	 .end();
}
//******************************************
// Load all friend to table
//******************************************
function loadallfriend(typerequire,tab) {	
	var $tableaddrow = tab,
	contentHTML = "",
	friend = $.configGlobal.AllFriend;
    if (!(friend instanceof Array)) {
        console.log("khong co ban nao trong danh sach");
        return false;
	}
    var friendsize = friend.length;		     
    if (friendsize < 1) {
        console.log("friend variable is empty");
        return false;
	}
	$tableaddrow.empty();	
	if (typerequire == 1) {	
		
        for (var i = 0; i < friendsize; i++) {
            var tempfriend = friend[i];			
            $tableaddrow.append('<div class="khungketbanul"><hr /><div class="khungketbanli" style="width:70%">{0}</div><div class="khungketbanli" style="width:30%"><a href="" id="xoaban{1}" onclick="DeleteFriend({1});return false;">Xóa bạn</a></div></div>'.format(tempfriend.MaBanBe2, tempfriend.MaKetBan));
			// $tableaddrow.append('<script>$("#xoaban").click(Test);</script>');
            // $tableaddrow.append('<script>$(function(){$("#xoaban{0}").click(DeleteFriend("{0}"));return false;});</script>'.format(tempfriend.MaKetBan));				
            tempfriend = null;
		}
		contentHTML = $tableaddrow.html();
		$('#test')
		.empty()
		.html(contentHTML);		
	}
    else {
        for (var i = 0; i < friendsize; i++) {
            var tempfriend = friend[i];
			
            $tableaddrow.append('<div class="khungketbanul"><hr /><div class="khungketbanli" style="width:400px">{0}</div><div class="khungketbanli" style="width:100px"><a href="" id="dongy{1}" onclick="agreemakefriend({1});return false;">Đồng ý</a></div><div class="khungketbanli" style="width:100px"><a href="" id="tuchoi{1}" onclick="DeleteFriend({1}); return false;">Từ chối</a></div></div>'.format(tempfriend.MaBanBe2, tempfriend.MaKetBan));
            // $tableaddrow.append('<script>$(function(){$("#dongy{0}").click(agreemakefriend("{0}"));$("#tuchoi{0}").click(DeleteFriend("{}"));return false;});</script>'.format(tempfriend.MaKetBan));
            tempfriend = null;
		}
		contentHTML = $tableaddrow.html();
        $('#test')
		.empty()
		.html(contentHTML);	
	}
	return false;
}

//******************************************
// Declare function to delete or refuse request make friend
//******************************************
function DeleteFriend(objma) {
    var tempma = objma;
    // Call api
    $.ajax({
        url: $.configGlobal.uriDeleteFriendAPI.format(tempma),
        type: $.configGlobal.protoDELETE,
        dataType: $.configGlobal.dataJSON,
        contentType: $.configGlobal.ctnJSON,
        success: function (data) {
            if (data == null) {
                console.log("returned data from delete friend api is empty !");
                return false;
			}
            btnshowfriendonClick();
            return false;
		},
        error: function (request, status, msg) {
            console.log(msg);
            return false;
		}
	});
    return false;
}
//******************************************
// Declare function to agree request make friend
//******************************************
function agreemakefriend(objmaketban) {
    var tempmaketban = objmaketban;
    var banbedata = {
        MaKetBan: tempmaketban
	};
    $.ajax({
        url: $.configGlobal.uriAgreeMakeFriendAPI,
        type: $.configGlobal.protoPUT,
        dataType: $.configGlobal.dataJSON,
        contentType: $.configGlobal.ctnJSON,
        data: JSON.stringify(banbedata),
        cache: false,
        async: false,
        success: function (response) {
            if (response == null) {
                console.log("return data form agree make friend api is empty !");
                return false;
			}
            else {
                //hien thi yeu cau ket ban hien tai.
                btnmakefriendonClick();
                return false;
			}
		},
        error: function (request, status, msg) {
            console.log(msg);
            return false;
		}
	});
    return false;
}
//******************************************
// Hien thi tim kiem ban
//******************************************
function btnfindfriendonClick() {
	//    var contenthtml = $('#trangtimkiemban').html();
    //    $('#test').empty().html(contenthtml);	
	var $tableaddrow = $($.configGlobal.tabFindFriend),
		textquery = $('#textqueryext').val();
    if (textquery == "") {
        $tableaddrow
			.empty()
			.append($('<div class="khungsearchfriend"><div class="searchfriend"><input id="textquery" type="text" value=""/></div><div class="btnsearchfriend"><a href="" id="btnsearchfriend">Search</a></div></div>'));
        $tableaddrow
			.append("<div class='khungketbanul'><div class='khungketbanli'>Bạn chưa nhập tên bạn bè cần tìm.</a></div></div>");
        $('#test')
			.empty()
			.html($tableaddrow.html());
        return false;
	}
    else {
		var email = $('#emailds').val();
        $.ajax({
            url: $.configGlobal.uriSearchFriendAPI.format(email, textquery),
            type: $.configGlobal.protoGET,
            dataType: $.configGlobal.dataJSON,
            contentType: $.configGlobal.ctnJSON,
            success: function (data) {
                if (data.length == 0) {
                    console.log("returned data from friend api is empty !");
                    var $tableaddrow = $($.configGlobal.tabReqFriend);
                    // $tableaddrow.empty();
                    // $tableaddrow.append("<div class='khungketbanul'><div class='khungketbanli'>Không tìm thấy bạn {0}.</a></div></div>".format(textquery));
					$tableaddrow = $('<div class="khungsearchfriend"><div class="searchfri"><div class="searchfriend"><input id="textqueryext" type="text" value="" /></div><div class="btnsearchfriend"><a href="" id="btnsearchfriend" onclick="btnfindfriendonClick();return false;">Search</a></div></div><div class="messagetext">Không tìm thấy tên cần tìm.</div></div>');
                    $('#test')
			        .empty()
			        .html($tableaddrow.html());
                    return false;
				}
                $.configGlobal.AllFriend = data;
                loadresultsearchfriend($($.configGlobal.tabFindFriend));
                return false;
			},
            error: function (request, status, msg) {
                console.log(msg);
                return false;
			}
		});
	}
    return false;
}
//******************************************
// Hien thi loi moi ket ban
//******************************************
function btnmakefriendonClick() {
    //var contenthtml = $('#trangloimoi').html();
    //$('.test').empty().html(contenthtml);
    email = $('#emailds').val();
    $.ajax({
        url: $.configGlobal.uriGetAllRequestFriendAPI.format(email),
        type: $.configGlobal.protoGET,
        dataType: $.configGlobal.dataJSON,
        contentType: $.configGlobal.ctnJSON,
        success: function (data) {
            if (data.length == 0) {
                console.log("returned data from friend api is empty !");
                var $tableaddrow = $($.configGlobal.tabReqFriend);
                $tableaddrow.empty();
                $tableaddrow.append("<div class='khungketbanul'><div class='khungketbanli'>Hiện bạn không có lời mời kết bạn nào.</a></div></div>");
                $('#test')
				.empty()
				.html($tableaddrow.html());
                return false;
			}
            typerequire = 2;
            $.configGlobal.AllFriend = data;
            loadallfriend(2, $($.configGlobal.tabReqFriend));
            return false;
		},
        error: function (request, status, msg) {
            console.log(msg);
            return false;
		}
	});
    return false;
}
//******************************************
// Show friend
//******************************************
function btnshowfriendonClick() {
	//    console.log("show friend on click");
    email = $('#emailds').val();
    $.ajax({
        url: $.configGlobal.uriGetAllFriendAPI.format(email),
        type: $.configGlobal.protoGET,
        dataType: $.configGlobal.dataJSON,
        contentType: $.configGlobal.ctnJSON,
        success: function (data) {
            if (data.length == 0) {
                console.log("returned data from friend api is empty !");
                //clearRowOfTable($('#tabshowallfriend'));
                var $tableaddrow = $($.configGlobal.tabAllFriend);
                $tableaddrow.empty();
                $tableaddrow.append("<div class='khungketbanul'><div class='khungketbanli'>Hiện bạn không có bạn bè nào. Hãy kết bạn thêm nhé !</div></div>");
                $('#test')
				.empty()
				.html($tableaddrow.html());
                return false;
			}
            $.configGlobal.AllFriend = data;
            loadallfriend(1, $($.configGlobal.tabAllFriend));
            return false;
		},
        error: function (request, status, msg) {
            console.log(msg);
            return false;
		}
	});
    return false;
}